var express = require('express');
var router = express.Router();
var fs = require("fs");
var path =require("path");


/* GET users listing. */
router.get('/', function(req, res, next) {
  const fpath = path.join(__dirname,"f.txt");
  res.locals.user = req.session.user ||"";
  res.locals.firstnum = Math.round(Math.random()*10);
  req.session.firstnum = res.locals.firstnum;
  res.locals.secondnum = Math.round(Math.random()*10);
  req.session.secondnum = res.locals.secondnum;
  res.locals.thirdnum = Math.round(Math.random()*10);
  req.session.thirdnum = res.locals.thirdnum;
  res.locals.fourthnum = Math.round(Math.random()*10);
  req.session.fourthnum = res.locals.fourthnum;
  // function run(fpath){
  //   let str = "123";
  //   fs.readFile(fpath,function(err,data){
  //     if(err){
  //       console.log(err);
  //     }else{
  //       str = data.toString();
  //       console.log(data.toString());
  //     }
  //   });
  //   return str;
  // }没有考虑异步，可能会出现一些问题 返回结果可能为空！
  res.locals.speak = fs.readFileSync(fpath,"utf8").toString();//读取文件和赋值同步进行，意思就是等待完全读取完文件后再进行赋值就不会产生空值的情况了
  res.render("user");
});

var users = {}

router.get("/logout",function(req,res){//退出路由
  req.session.user = undefined;
  res.redirect("back");
});

router.post("/login",function(req,res){//登陆路由
  const {loginname,password ,vnum} = req.body;
  if(Number(vnum) === (req.session.firstnum + req.session.secondnum) && users[loginname] && users[loginname].password === password){
    req.session.user = {loginname}
  }
  res.redirect("back");
});


router.post("/reg",function(req,res){//注册路由
  const {loginname , password , confirm,xnum} = req.body;
  if(Number(xnum) === (req.session.thirdnum + req.session.fourthnum) && loginname && password && password === confirm){
    users[loginname] = {loginname,password}
  }
  res.redirect("back");
});

router.post("/refresh",function(req,res){//储存路由
  const {text} = req.body;
  const fpath = path.join(__dirname,"f.txt");
  const speak = req.session.user.loginname + ": " + text + '\n';
  fs.appendFile(fpath,speak,function(err){
    console.log(err);
  });
  res.redirect("back");
});

module.exports = router;
